<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Iterators</title>
</head>
<body>
<?php
/**
 * 这是个用来演示迭代器的文件，要让类拥有迭代功能只需实现Iterator接口即可，这样就可以用foreach来遍历了
 * User: ford
 * Date: 15-8-11
 * Time: 下午4:25
 */
class Department implements Iterator {
	private $_name;
	private $_employees;

	//用于迭代器的计数变量
	private $_position = 0;

	function __construct($name) {
		$this->_name = $name;
		$this->_employees = array();
		$this->_position = 0;
	}

	function addEmployee(Employee $e) {
		$this->_employees[] = $e;
		echo "<p>{$e->getName()} has been added to the {$this->_name} departments.</p>";
	}

	//下面是Iterator接口要实现的方法
	function current() {
		return $this->_employees[$this->_position];
	}

	function key() {
		return $this->_position;
	}

	function next() {
		$this->_position++;
	}

	function rewind() {
		$this->_position = 0;
	}

	function valid() {
		return (isset($this->_employees[$this->_position]));
	}
}

class Employee {
	private $_name;

	function __construct($name) {
		$this->_name = $name;
	}

	function getName() {
		return $this->_name;
	}
}

//下面是使用代码
$hr = new Department('Human Resources');

$e1 = new Employee('Jane Doe');
$e2 = new Employee('John Doe');

$hr->addEmployee($e1);
$hr->addEmployee($e2);

echo "<h2>Department Employees</h2>";
//下面就可以直接用foreach来遍类Deparment类了
foreach($hr as $e) {
	echo "<p>{$e->getName()}</p>";
}

unset($h1, $e1, $e2);
?>
</body>
</html>
